<template>
  <div class="p-2 sm:p-4">
    <!-- 错误提示 -->
    <div v-if="error" class="flex items-center p-3 mb-4 bg-red-100 border border-red-200 rounded-md text-red-700 text-sm">
      <span class="mr-2">⚠️</span>
      {{ error }}
    </div>
    <!-- 响应式布局：桌面端使用水平布局，移动端使用垂直布局 -->
    <div class="flex flex-col lg:flex-row gap-4">
      <!-- 绘图区域和操作按钮 -->
      <div class="flex-1 flex flex-col gap-4">
        <!-- 绘图区域 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden relative" :class="{ 'preview-mode': previewMode }">
          <div ref="excalidrawContainer" class="w-full h-[85vh] md:h-[85vh]"></div>

          <!-- 移动端浮动操作按钮 -->
          <div
              v-if="isMobile"
              ref="floatingButton"
              class="fixed bg-white/90 backdrop-blur-sm border border-gray-200/50 rounded-full shadow-lg flex items-center justify-center cursor-pointer transition-all duration-200 hover:bg-white hover:shadow-xl hover:scale-105 active:scale-95"
              :style="floatingButtonStyle"
              :class="floatingButtonClasses"
              @touchstart="startDrag"
              @touchmove="onDrag"
              @touchend="endDrag"
              @mousedown="startDrag"
              @mousemove="onDrag"
              @mouseup="endDrag"
              @click="toggleActionMenu"
          >
            <svg class="w-4 h-4 text-gray-600" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
            </svg>
          </div>

          <!-- 移动端操作菜单弹窗 -->
          <div v-if="showActionMenu && isMobile" class="fixed inset-0 bg-black/20 backdrop-blur-sm flex items-center justify-center z-[9999]" @click="closeActionMenu">
            <div class="bg-white/95 backdrop-blur-md rounded-2xl shadow-2xl border border-gray-200/50 p-6 mx-4" @click.stop>
              <div class="grid grid-cols-3 gap-4">
                <button
                    v-for="action in mobileActions"
                    :key="action.key"
                    @click="executeAction(action)"
                    :disabled="action.disabled"
                    :title="action.title"
                    class="flex flex-col items-center gap-2 p-3 rounded-xl transition-all duration-200 hover:scale-105 active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed border border-gray-200 hover:border-gray-300 hover:shadow-md"
                    :class="action.disabled ? 'bg-gray-100' : 'bg-white hover:bg-gray-50'"
                >
                  <div class="w-8 h-8 rounded-lg flex items-center justify-center" :class="action.iconBgClass">
                    <component :is="getIconComponent(action.icon)" class="w-5 h-5 text-white" />
                  </div>
                  <span class="text-xs font-medium text-gray-700 text-center leading-tight">{{ action.label }}</span>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 移动端显示已保存的绘图 -->
        <div class="sm:hidden mt-4">
          <div class="text-center font-medium text-gray-800 mb-2" @click.stop="resetForm(true)">已保存的{{ isDrafting?`草稿`:`绘图` }}
            <a-switch v-model:checked="isDrafting"  style="float:right" checked-children="看草稿" un-checked-children="看绘图" />
          </div>

          <!-- 移动端搜索框 -->
          <div class="mb-3">
            <a-input
                v-model:value="searchQuery"
                placeholder="搜索标题..."
                allow-clear
                @change="handleSearch"
                class="rounded-lg"
            >
              <template #suffix>
                <svg class="w-4 h-4 text-gray-400" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                </svg>
              </template>
            </a-input>
          </div>

          <div v-if="filteredDraftList.length === 0&&(isDrafting )" class="text-gray-500 text-center italic">暂无保存的草稿</div>
          <div v-if="filteredRemoteList.length === 0&&(!isDrafting )" class="text-gray-500 text-center italic">暂无保存的绘图</div>

          <!-- 移动端草稿列表 -->
          <div class="space-y-3" v-if="filteredDraftList.length > 0 && (isDrafting)">
            <div
                v-for="drawing in filteredDraftList"
                :key="drawing.id"
                class="border border-gray-200 rounded-lg bg-white hover:bg-gray-50 transition-colors p-3 cursor-pointer"
                :class="{ 'ring-2 ring-blue-500 bg-blue-50': saveForm.id === drawing.id }"
                @click="selectAndLoadDrawing(drawing)"
            >
              <!-- 标题行 -->
              <div class="flex items-center justify-between mb-2">
                <div
                    class="font-medium text-gray-800 truncate flex-1 mr-2"
                    :title="drawing.title"
                >
                  {{ drawing.title }}
                </div>
                <div class="flex items-center gap-2">
                  <!-- 关联图标 -->
                  <div class="flex items-center gap-1">
                    <svg v-if="drawing.blogId" class="w-4 h-4 text-blue-500" viewBox="0 0 24 24" fill="currentColor" title="已关联博客">
                      <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
                    </svg>
                    <svg v-if="drawing.projectId" class="w-4 h-4 text-green-500" viewBox="0 0 24 24" fill="currentColor" title="已关联项目经历">
                      <path d="M20 6h-2.18c.11-.31.18-.65.18-1a2.996 2.996 0 0 0-5.5-1.65l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1z"/>
                    </svg>
                  </div>
                  <!-- 删除按钮 -->
                    <button
                        class="text-red-500 hover:text-red-700 p-1"
                        title="删除草稿"
                        @click="$_confirm('删除确认','确定要删除这条数据吗？',()=>{
                      deleteDrawing(drawing)
                      })"
                    >
                      <svg class="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                      </svg>
                    </button>
                </div>
              </div>

              <!-- 描述 -->
              <div
                  v-if="drawing.description"
                  class="text-sm text-gray-600 mb-2 line-clamp-2"
                  :title="drawing.description"
              >
                {{ drawing.description }}
              </div>

              <!-- 底部信息 -->
              <div class="flex items-center justify-between text-xs text-gray-500">
                <span>{{ $formatDate(drawing.createdAt) }}</span>
                <div class="flex items-center gap-1">
                  <svg class="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                  </svg>
                  <span>{{ drawing.browseNumber&&drawing.browseNumber>999?'999+':drawing.browseNumber || 0 }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 移动端远程绘图列表 -->
          <div v-else class="space-y-3" v-if="filteredRemoteList.length > 0&&(!isDrafting)">
            <div
                v-for="drawing in filteredRemoteList"
                :key="drawing.id"
                class="border border-gray-200 rounded-lg bg-white hover:bg-gray-50 transition-colors p-3 cursor-pointer"
                :class="{ 'ring-2 ring-blue-500 bg-blue-50': saveForm.id === drawing.id }"
                @click="selectAndLoadDrawing(drawing)"
            >
              <!-- 标题行 -->
              <div class="flex items-center justify-between mb-2">
                <div
                    class="font-medium text-gray-800 truncate flex-1 mr-2"
                    :title="drawing.title"
                >
                  {{ drawing.title }}
                </div>
                <div class="flex items-center gap-2">
                  <!-- 关联图标 -->
                  <div class="flex items-center gap-1">
                    <svg v-if="drawing.blogId" class="w-4 h-4 text-blue-500" viewBox="0 0 24 24" fill="currentColor" title="已关联博客">
                      <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
                    </svg>
                    <svg v-if="drawing.projectId" class="w-4 h-4 text-green-500" viewBox="0 0 24 24" fill="currentColor" title="已关联项目经历">
                      <path d="M20 6h-2.18c.11-.31.18-.65.18-1a2.996 2.996 0 0 0-5.5-1.65l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1z"/>
                    </svg>
                  </div>
                  <!-- 删除按钮 -->
                    <button
                        class="text-red-500 hover:text-red-700 p-1"
                        title="删除绘图"
                        @click="$_confirm('删除确认','确定要删除这条数据吗？',()=>{
                      deleteDrawing(drawing)
                      })"
                        @click.stop
                    >
                      <svg class="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                      </svg>
                    </button>
                </div>
              </div>

              <!-- 描述 -->
              <div
                  v-if="drawing.description"
                  class="text-sm text-gray-600 mb-2 line-clamp-2"
                  :title="drawing.description"
              >
                {{ drawing.description }}
              </div>

              <!-- 底部信息 -->
              <div class="flex items-center justify-between text-xs text-gray-500">
                <span>{{ $formatDate(drawing.createdAt) }}</span>
                <div class="flex items-center gap-1">
                  <svg class="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                  </svg>
                  <span>{{ drawing.browseNumber&&drawing.browseNumber>999?'999+':drawing.browseNumber || 0 }}</span>
                </div>
              </div>
            </div>

            <!-- 移动端加载更多按钮 -->
            <div v-if="!isDrafting && hasMoreRemote" class="text-center py-4">
              <a-button
                  @click="loadMoreRemote"
                  :loading="loadingMore"
                  type="dashed"
                  class="w-full"
              >
                {{ loadingMore ? '加载中...' : '加载更多' }}
              </a-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧边栏 - 只在大屏幕上显示 -->
      <div class="hidden lg:flex lg:w-64 flex-col gap-4">
        <div class="bg-white rounded-lg shadow-sm overflow-hidden h-[62vh] flex flex-col">
          <div class="px-4 py-3 font-semibold border-b border-gray-100 bg-gray-50 flex-shrink-0" @click.stop="resetForm(true)">
            已保存的{{ isDrafting?`草稿`:`绘图` }}
            <a-switch v-model:checked="isDrafting"   style="float:right" checked-children="看草稿" un-checked-children="看绘图" />
          </div>

          <!-- 桌面端搜索框 -->
          <div class="p-3 border-b border-gray-100 flex-shrink-0">
            <a-input
                v-model:value="searchQuery"
                placeholder="搜索标题..."
                allow-clear
                @change="handleSearch"
                size="small"
                class="rounded-md"
            >
              <template #prefix>
                <PlusSquareOutlined @click="resetForm(true)" />
              </template>
              <template #suffix>
                <svg class="w-3 h-3 text-gray-400" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                </svg>
              </template>
            </a-input>
          </div>

          <div class="flex-1 overflow-y-auto overflow-x-hidden p-4" style="scrollbar-width: thin;-ms-overflow-style: none;">
            <p v-if="filteredDraftList.length === 0&&(isDrafting  )" class="text-gray-500 text-center italic">暂无保存的草稿</p>
            <p v-if="filteredRemoteList.length === 0&&(!isDrafting )" class="text-gray-500 text-center italic">暂无保存的绘图</p>

            <!-- 桌面端草稿列表 -->
            <div class="flex flex-col gap-3" v-if="filteredDraftList.length>0&&(isDrafting )">
              <div
                  v-for="drawing in filteredDraftList"
                  :key="drawing.id"
                  class="border border-gray-100 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors p-3 cursor-pointer"
                  :class="{ 'ring-2 ring-blue-500 bg-blue-100': saveForm.id === drawing.id }"
                  @click="selectAndLoadDrawing(drawing)"
              >
                <!-- 标题行 -->
                <div class="flex items-center justify-between mb-2">
                  <div
                      class="font-medium text-gray-800 truncate flex-1 mr-2 text-sm"
                      :title="drawing.title"
                  >
                    {{ drawing.title }}
                  </div>
                  <div class="flex items-center gap-1">
                    <!-- 关联图标 -->
                    <svg v-if="drawing.blogId" class="w-3 h-3 text-blue-500" viewBox="0 0 24 24" fill="currentColor" title="已关联博客">
                      <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
                    </svg>
                    <svg v-if="drawing.projectId" class="w-3 h-3 text-green-500" viewBox="0 0 24 24" fill="currentColor" title="已关联项目经历">
                      <path d="M20 6h-2.18c.11-.31.18-.65.18-1a2.996 2.996 0 0 0-5.5-1.65l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1z"/>
                    </svg>
                    <!-- 删除按钮 -->
                      <button
                          class="text-red-500 hover:text-red-700 p-0.5"
                          title="删除草稿"
                          @click="$_confirm('删除确认','确定要删除这条数据吗？',()=>{
                            deleteDrawing(drawing)
                            })"
                      >
                        <svg class="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                          <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                        </svg>
                      </button>
                  </div>
                </div>

                <!-- 描述 -->
                <div
                    v-if="drawing.description"
                    class="text-xs text-gray-600 mb-2 line-clamp-2"
                    :title="drawing.description"
                >
                  {{ drawing.description }}
                </div>

                <!-- 底部信息 -->
                <div class="flex items-center justify-between text-xs text-gray-500">
                  <span>{{ $formatDate(drawing.createdAt) }}</span>
                  <div class="flex items-center gap-1">
                    <svg class="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                    </svg>
                    <span>{{ drawing.browseNumber&&drawing.browseNumber>999?'999+':drawing.browseNumber || 0 }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 桌面端远程绘图列表 -->
            <div class="flex flex-col gap-3" v-if="filteredRemoteList.length>0&&(!isDrafting)" >
              <div
                  v-for="drawing in filteredRemoteList"
                  :key="drawing.id"
                  class="border border-gray-100 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors p-3 cursor-pointer"
                  :class="{ 'ring-2 ring-blue-500 bg-blue-100': saveForm.id === drawing.id }"
                  @click="selectAndLoadDrawing(drawing)"
              >
                <!-- 标题行 -->
                <div class="flex items-center justify-between mb-2">
                  <div
                      class="font-medium text-gray-800 truncate flex-1 mr-2 text-sm"
                      :title="drawing.title"
                  >
                    {{ drawing.title }}
                  </div>
                  <div class="flex items-center gap-1">
                    <!-- 关联图标 -->
                    <svg v-if="drawing.blogId" class="w-3 h-3 text-blue-500" viewBox="0 0 24 24" fill="currentColor" title="已关联博客">
                      <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
                    </svg>
                    <svg v-if="drawing.projectId" class="w-3 h-3 text-green-500" viewBox="0 0 24 24" fill="currentColor" title="已关联项目经历">
                      <path d="M20 6h-2.18c.11-.31.18-.65.18-1a2.996 2.996 0 0 0-5.5-1.65l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1z"/>
                    </svg>
                    <!-- 删除按钮 -->
                      <button
                          class="text-red-500 hover:text-red-700 p-0.5"
                          title="删除绘图"
                          @click="$_confirm('删除确认','确定要删除这条数据吗？',()=>{
                            deleteDrawing(drawing)
                            })"
                      >
                        <svg class="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                          <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                        </svg>
                      </button>
                  </div>
                </div>

                <!-- 描述 -->
                <div
                    v-if="drawing.description"
                    class="text-xs text-gray-600 mb-2 line-clamp-2"
                    :title="drawing.description"
                >
                  {{ drawing.description }}
                </div>

                <!-- 底部信息 -->
                <div class="flex items-center justify-between text-xs text-gray-500">
                  <span>{{ $formatDate(drawing.createdAt) }}</span>
                  <div class="flex items-center gap-1">
                    <svg class="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                    </svg>
                    <span>{{ drawing.browseNumber&&drawing.browseNumber>999?'999+':drawing.browseNumber || 0 }}</span>
                  </div>
                </div>
              </div>

              <!-- 桌面端加载更多按钮 -->
              <div v-if="hasMoreRemote" class="text-center py-2">
                <a-button
                    @click="loadMoreRemote"
                    :loading="loadingMore"
                    type="dashed"
                    size="small"
                    class="w-full"
                >
                  {{ loadingMore ? '加载中...' : '加载更多' }}
                </a-button>
              </div>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
          <div class="px-4 py-3 font-semibold border-b border-gray-100 bg-gray-50">使用说明</div>
          <div class="p-4">
            <ul class="list-disc pl-5 space-y-1">
              <li class="text-sm text-gray-700">使用工具栏绘制各种形状</li>
              <li class="text-sm text-gray-700">移动端点击浮动按钮打开菜单</li>
              <li class="text-sm text-gray-700">支持全屏模式和预览模式</li>
              <li class="text-sm text-gray-700">预览模式禁用所有编辑功能</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <a-modal v-model:open="showSaveModal" @cancel="cancelSave" :closable="false">
      <a-card :title="'绘图管理'">
        <a-form
            style="margin: 4px 4px"
            ref="formRef"
            :model="saveForm"
            autocomplete="off"
        >
          <a-form-item name="title"  :rules="[{ required: true,message:'请输入标题', }]">
            <a-input placeholder="取个标题" v-model:value="saveForm.title"  />
          </a-form-item>
          <a-form-item name="description">
            <a-textarea placeholder="要不来个描述?" v-model:value="saveForm.description"  />
          </a-form-item>
          <a-form-item  name="blogId"   v-if="state.user?.id">
            <a-select v-model:value="saveForm.blogId" show-search @search="loadBlogList" :filter-option="false" placeholder="关联博客">
              <a-select-option v-for="item in blogData" :value="item.id">{{ item.title }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item name="projectId"   v-if="state.user?.id">
            <a-select v-model:value="saveForm.projectId" show-search @search="loadProjectList"  :filter-option="false" placeholder="关联项目">
              <a-select-option v-for="item in projectData" :value="item.id">{{ item.title }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-card>
      <template #footer>
        <a-button type="primary"  @click="cancelSave" style="float:left" default>取消</a-button>
        <a-button type="dashed" @click="confirmSave(true)" v-if="saveForm.local">保存为草稿</a-button>
        <a-button type="primary"  @click="confirmSave(false)"   v-if="state.user?.id">保存</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onBeforeUnmount, nextTick, watch, computed, h} from 'vue';
import { Excalidraw } from '@excalidraw/excalidraw';
import "@excalidraw/excalidraw/index.css";
import {graphList, graphSave, graphDel, graphCheck} from "@/api/blog/graph.js";
import {blogList} from "@/api/blog.js";
import {projectList} from "@/api/user.js";
import {useAuthStore} from '@/store/auth';
const {state} = useAuthStore();

// 状态变量
const excalidrawContainer = ref(null);
const excalidrawAPI = ref(null);

const error = ref('');
const previewMode = ref(false);
const isDrafting = ref(false)
const isFullscreen = ref(false);
const isMobile = ref(false);
let previewModeObserver = null;
import { PlusSquareOutlined } from '@ant-design/icons-vue';

// 新增：搜索和选中状态
const searchQuery = ref('');
const loadingMore = ref(false);

// 浮动按钮相关
const floatingButton = ref(null);
const showActionMenu = ref(false);
const isDragging = ref(false);
const dragOffset = ref({ x: 0, y: 0 });
const buttonPosition = ref({ x: 0, y: 0 });

// 保存弹窗相关
const showSaveModal = ref(false);
const formRef = ref(null)
const saveForm = reactive({
  title: '',
  description: '',
  blogId: undefined,
  projectId: undefined,
  local:true,
  createdAt: 0,
  accountId:undefined,
  id: '',
});

const resetForm = (flag) => {
  saveForm.id =""
  saveForm.title =""
  saveForm.projectId =undefined
  saveForm.blogId =undefined
  saveForm.description =""
  saveForm.local = true
  saveForm.createdAt = 0
  if(excalidrawAPI.value&&flag!==true){
    clearCanvas()
  }
}

// 浮动按钮样式和类
const floatingButtonStyle = computed(() => ({
  right: `${10}px`,
  top: `${buttonPosition.value.y}px`,
  width: '28px',
  height: '51px',
}));

watch(isDrafting,(val)=>{
  if(!val){
    pageNum.value = 1
    loadDrawings()
  }
  resetForm()
  searchQuery.value = ''; // 切换时清空搜索
})

const floatingButtonClasses = computed(() => ({
  'z-[9998]': !isFullscreen.value,
  'z-[10003]': isFullscreen.value,
}));

// 新增：过滤后的列表
const filteredDraftList = computed(() => {
  if (!searchQuery.value.trim()) {
    return draftList.value;
  }
  return draftList.value.filter(item =>
      item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

const filteredRemoteList = computed(() => {
  if (!searchQuery.value.trim()) {
    return remoteList.value;
  }
  return remoteList.value.filter(item =>
      item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 新增：是否还有更多远程数据
const hasMoreRemote = computed(() => {
  return remoteList.value.length < remoteTotal.value;
});

// 图标组件映射
const iconComponents = {
  save: () => h('svg', { viewBox: '0 0 24 24', fill: 'currentColor' }, [
    h('path', { d: 'M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z' })
  ]),
  eye: () => h('svg', { viewBox: '0 0 24 24', fill: 'currentColor' }, [
    h('path', { d: 'M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z' })
  ]),
  edit: () => h('svg', { viewBox: '0 0 24 24', fill: 'currentColor' }, [
    h('path', { d: 'M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z' })
  ]),
  expand: () => h('svg', { viewBox: '0 0 24 24', fill: 'currentColor' }, [
    h('path', { d: 'M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z' })
  ]),
  shrink: () => h('svg', { viewBox: '0 0 24 24', fill: 'currentColor' }, [
    h('path', { d: 'M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z' })
  ]),
  trash: () => h('svg', { viewBox: '0 0 24 24', fill: 'currentColor' }, [
    h('path', { d: 'M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z' })
  ]),
  download: () => h('svg', { viewBox: '0 0 24 24', fill: 'currentColor' }, [
    h('path', { d: 'M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z' })
  ])
};

// 获取图标组件
const getIconComponent = (iconName) => {
  return iconComponents[iconName] || iconComponents.save;
};

// 移动端操作配置
const mobileActions = computed(() => [
  {
    key: 'save',
    label: '保存',
    title: '保存绘图',
    onClick: showSaveDialog,
    disabled: previewMode.value,
    icon: 'save',
    iconBgClass: 'bg-gradient-to-br from-purple-500 to-purple-600'
  },
  {
    key: 'preview',
    label: previewMode.value ? '编辑' : '预览',
    title: previewMode.value ? '退出预览' : '预览模式',
    onClick: togglePreviewMode,
    disabled: false,
    icon: previewMode.value ? '👁️' : '👁️',
    iconBgClass: previewMode.value
        ? 'bg-gradient-to-br from-green-500 to-green-600'
        : 'bg-gradient-to-br from-blue-500 to-blue-600'
  },
  {
    key: 'fullscreen',
    label: isFullscreen.value ? '退出' : '全屏',
    title: isFullscreen.value ? '退出全屏' : '进入全屏',
    onClick: toggleFullscreen,
    disabled: false,
    icon: isFullscreen.value ? 'shrink' : 'expand',
    iconBgClass: 'bg-gradient-to-br from-indigo-500 to-indigo-600'
  },
  {
    key: 'clear',
    label: '清空',
    title: '清空画布',
    onClick: clearCanvas,
    disabled: previewMode.value,
    icon: 'trash',
    iconBgClass: 'bg-gradient-to-br from-red-500 to-red-600'
  },
  {
    key: 'export-png',
    label: '导出',
    title: '导出PNG',
    onClick: exportToPNG,
    disabled: false,
    icon: 'download',
    iconBgClass: 'bg-gradient-to-br from-emerald-500 to-emerald-600'
  }
]);

// 检测是否为移动设备
const checkMobile = () => {
  isMobile.value = window.innerWidth < 768;
};

// 计算浮动按钮位置
const calculateButtonPosition = () => {
  if (!isMobile.value || !excalidrawContainer.value) return;

  const containerRect = excalidrawContainer.value.getBoundingClientRect();
  const viewportHeight = window.innerHeight;

  // 使用用户指定的位置：right: 10px, top: 80vh
  buttonPosition.value = {
    x: 10, // right: 10px
    y: Math.min(viewportHeight * 0.8, containerRect.height * 0.8) // top: 80vh，但不超过容器高度
  };
};

// 新增：搜索处理函数
const handleSearch = () => {
  // 搜索是通过计算属性实现的，这里可以添加额外的搜索逻辑
  // 比如防抖、远程搜索等
  if (!isDrafting.value && searchQuery.value.trim()) {
    // 如果是远程搜索，可以在这里重新加载数据
    pageNum.value = 1;
    queryForm.value.title = searchQuery.value.trim();
    loadRemoteDrawings();
  } else if (!isDrafting.value && !searchQuery.value.trim()) {
    // 清空搜索时重新加载
    queryForm.value.title = undefined;
    pageNum.value = 1;
    loadRemoteDrawings();
  }
};

// 新增：选中并加载绘图
const selectAndLoadDrawing = (drawing) => {
  loadDrawing(drawing);
};

// 新增：加载更多远程数据
const loadMoreRemote = async () => {
  if (loadingMore.value || !hasMoreRemote.value) return;
  loadingMore.value = true;
  try {
    pageNum.value += 1;
    const res = await graphList(Object.assign({page:{pageNum: pageNum.value, pageSize: pageSize.value}}, queryForm.value));
    if (res && res.code === 200) {
      const data = res.data || {};
      const newList = data.list || [];
      remoteList.value = [...remoteList.value, ...newList];
      remoteTotal.value = data.total || 0;
    }
  } catch (error) {
    console.error('加载更多数据失败:', error);
    pageNum.value -= 1; // 回退页码
  } finally {
    loadingMore.value = false;
  }
};

// 浮动按钮拖拽功能
const startDrag = (e) => {
  if (e.type === 'mousedown' && e.button !== 0) return;

  isDragging.value = true;
  const clientX = e.type.includes('touch') ? e.touches[0].clientX : e.clientX;
  const clientY = e.type.includes('touch') ? e.touches[0].clientY : e.clientY;

  dragOffset.value = {
    x: clientX - (window.innerWidth - buttonPosition.value.x - 28), // 考虑right定位
    y: clientY - buttonPosition.value.y
  };

  e.preventDefault();
};

const onDrag = (e) => {
  if (!isDragging.value) return;

  const clientX = e.type.includes('touch') ? e.touches[0].clientX : e.clientX;
  const clientY = e.type.includes('touch') ? e.touches[0].clientY : e.clientY;

  const container = excalidrawContainer.value;
  if (!container) return;

  const rect = container.getBoundingClientRect();
  const newX = Math.max(10, Math.min(rect.width - 38, window.innerWidth - clientX + dragOffset.value.x - 28));
  const newY = Math.max(0, Math.min(rect.height - 51, clientY - rect.top - dragOffset.value.y));

  buttonPosition.value = { x: newX, y: newY };
  e.preventDefault();
};

const endDrag = (e) => {
  if (!isDragging.value) return;

  isDragging.value = false;
  e.preventDefault();

  // 如果是轻微移动，则视为点击
  const moveThreshold = 5;
  const clientX = e.type.includes('touch') ? e.changedTouches[0].clientX : e.clientX;
  const clientY = e.type.includes('touch') ? e.changedTouches[0].clientY : e.clientY;

  const moveDistance = Math.sqrt(
      Math.pow(clientX - (window.innerWidth - buttonPosition.value.x - 28 + dragOffset.value.x), 2) +
      Math.pow(clientY - (buttonPosition.value.y + dragOffset.value.y), 2)
  );

  if (moveDistance < moveThreshold) {
    setTimeout(() => toggleActionMenu(), 0);
  }
};

// 操作菜单功能
const toggleActionMenu = () => {
  if (isDragging.value) return;
  showActionMenu.value = !showActionMenu.value;
};

const closeActionMenu = () => {
  showActionMenu.value = false;
};

const executeAction = (action) => {
  if (action.disabled) return;

  closeActionMenu();
  action.onClick();
};

// 从 localStorage 加载保存的绘图
const loadDrawings =  () => {
  try {
    loadRemoteDrawings()
    loadLocalDrawings()
  } catch (e) {
    console.error('Failed to load saved drawings:', e);
    error.value = '加载保存的绘图失败';
  }
};

const pageNum =ref(1)
const pageSize = ref(6)
const queryForm = ref({title:undefined})
const remoteTotal = ref(0)
const remoteList = ref([])

const loadRemoteDrawings =  () => {
  graphList(Object.assign({page:{pageNum: pageNum.value, pageSize: pageSize.value}},queryForm.value)).then(res=>{
    if(res&&res.code==200){
      const data = res.data || {}
      if (pageNum.value === 1) {
        remoteList.value = data.list || []
      } else {
        remoteList.value = [...remoteList.value, ...(data.list || [])]
      }
      remoteTotal.value = data.total || 0
    }
  }).finally(()=>{
  })
};

const draftList = ref([]);
const loadLocalDrawings = () => {
  try {
    const savedData = localStorage.getItem('excalidraw-demo');
    if (savedData) {
      let data = JSON.parse(savedData)
      data.map(item => {
        item.local = true
        item.content = item.content || JSON.stringify(item.elements)
        item.title = item.title || item.name
      })
      draftList.value = data;
    }
  } catch (e) {
    console.error('Failed to load saved draft drawings:', e);
    error.value = '加载保存的草稿绘图失败';
  }
}

// 创建自定义工具栏按钮组件（桌面端使用）
const createCustomButton = (React, icon, title, onClick, className = '') => {
  const buttonPadding = '6px';
  const buttonSize = '28px';
  const fontSize = '12px';

  return React.createElement('button', {
    className: `custom-toolbar-button ${className}`,
    title: title,
    onClick: (e) => {
      console.log('Custom button clicked:', title);
      onClick(e);
    },
    style: {
      background: 'white',
      border: '1px solid #3b82f6',
      borderRadius: '4px',
      paddingTop: buttonPadding,
      paddingRight: buttonPadding,
      paddingBottom: buttonPadding,
      paddingLeft: buttonPadding,
      marginTop: '0',
      marginRight: '2px',
      marginBottom: '0',
      marginLeft: '2px',
      cursor: 'pointer',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: fontSize,
      fontWeight: '600',
      color: '#1f2937',
      transition: 'all 0.15s',
      boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
      minWidth: buttonSize,
      height: buttonSize,
      zIndex: 1000,
    },
    onMouseEnter: (e) => {
      e.target.style.backgroundColor = '#dbeafe';
      e.target.style.borderColor = '#2563eb';
      e.target.style.transform = 'scale(1.02)';
    },
    onMouseLeave: (e) => {
      e.target.style.backgroundColor = 'white';
      e.target.style.borderColor = '#3b82f6';
      e.target.style.transform = 'scale(1)';
    }
  }, icon);
};

watch(
    () => state.user?.id,
    (newId, oldId) => {
      resetForm()
    }
)

// 获取桌面端按钮配置
const getDesktopButtons = () => {
  return [
    { key: 'save', icon: '💾', title: '保存绘图', onClick: showSaveDialog },
    { key: 'preview', icon: '👁️', title: previewMode.value ? '退出预览' : '预览模式', onClick: togglePreviewMode },
    { key: 'fullscreen', icon: isFullscreen.value ? '🔍' : '⛶', title: isFullscreen.value ? '退出全屏' : '进入全屏', onClick: toggleFullscreen },
    { key: 'clear', icon: '🗑️', title: '清空画布', onClick: clearCanvas },
  ];
};

// 自定义顶部右侧UI组件（仅桌面端）
const renderTopRightUI = (React) => {
  if (isMobile.value) return null; // 移动端不显示顶部按钮

  console.log('Rendering top right UI for desktop');
  const buttons = getDesktopButtons();

  return React.createElement('div', {
    style: {
      display: 'flex',
      alignItems: 'center',
      gap: '2px',
      paddingTop: '2px',
      paddingRight: '4px',
      paddingBottom: '2px',
      paddingLeft: '4px',
      flexWrap: 'nowrap',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderRadius: '6px',
      border: '1px solid #e5e7eb',
      zIndex: 1000,
    }
  }, buttons.map(button =>
      React.createElement('div', { key: button.key },
          createCustomButton(React, button.icon, button.title, button.onClick, button.key + '-btn')
      )
  ));
};

// 初始化 Excalidraw
onMounted(async () => {
  try {
    // 检测移动设备
    checkMobile();

    // 设置浮动按钮默认位置
    calculateButtonPosition();

    // 设置 Excalidraw 资源路径
    window.EXCALIDRAW_ASSET_PATH = "/";

    // 加载保存的绘图
    loadDrawings();

    // 确保容器已经渲染
    await nextTick();

    // 动态导入 React 和 ReactDOM
    const React = await import('react');
    const ReactDOM = await import('react-dom/client');

    // 创建 React 根元素
    const root = ReactDOM.createRoot(excalidrawContainer.value);

    // 渲染 Excalidraw 组件
    root.render(
        React.createElement(Excalidraw, {
          excalidrawAPI: (api) => {
            excalidrawAPI.value = api;
            console.log('Excalidraw loaded successfully', api);
          },
          initialData: {
            elements: [],
            appState: {
              viewBackgroundColor: '#ffffff',
              currentItemStrokeColor: '#000000',
              currentItemBackgroundColor: '#ffffff',
              collaborators: [],
              currentItemFontFamily: 1,
              theme: 'light',
              width: excalidrawContainer.value.clientWidth,
              height: excalidrawContainer.value.clientHeight,
              zoom: {
                value: 1,
              },
            },
          },
          gridModeEnabled: true,
          theme: 'light',
          name: 'Excalidraw Vue Demo Enhanced',
          UIOptions: {
            canvasActions: {
              export: false,
              saveAsScene: false,
              loadScene: false,
              clearCanvas: false,
            },
            tools: {
              image: isMobile.value ? false : true,
            },
          },
          renderTopRightUI: () => renderTopRightUI(React),
          onResize: () => {
            if (excalidrawAPI.value) {
              excalidrawAPI.value.updateScene({
                appState: {
                  width: excalidrawContainer.value.clientWidth,
                  height: excalidrawContainer.value.clientHeight,
                }
              });
            }
          },
          viewModeEnabled: previewMode.value,
          readOnly: previewMode.value,
        })
    );

    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize);

    // 检测是否为移动设备并优化界面
    optimizeForMobile();
  } catch (e) {
    console.error('Failed to initialize Excalidraw:', e);
    error.value = `初始化 Excalidraw 失败: ${e.message}`;
  }
});

// 监视预览模式变化
watch(previewMode, (newValue) => {
  if (newValue) {
    enablePreviewMode();
  } else {
    disablePreviewMode();
  }
});

// 监视全屏模式变化，确保浮动按钮可见
watch(isFullscreen, (newValue) => {
  nextTick(() => {
    if (isMobile.value) {
      calculateButtonPosition();
    }
  });
});

// 启用预览模式
const enablePreviewMode = () => {
  if (!excalidrawAPI.value) return;

  excalidrawAPI.value.updateScene({
    appState: {
      viewModeEnabled: true,
      readOnly: true,
      gridModeEnabled: false,
    }
  });

  hideExcalidrawUI();
  setupPreviewModeObserver();
};

// 禁用预览模式
const disablePreviewMode = () => {
  if (!excalidrawAPI.value) return;

  if (previewModeObserver) {
    previewModeObserver.disconnect();
    previewModeObserver = null;
  }

  excalidrawAPI.value.updateScene({
    appState: {
      viewModeEnabled: false,
      readOnly: false,
      gridModeEnabled: true,
    }
  });

  showExcalidrawUI();
};

// 隐藏 Excalidraw UI 元素
const hideExcalidrawUI = () => {
  setTimeout(() => {
    if (!excalidrawContainer.value) return;

    const menuButton = excalidrawContainer.value.querySelector('.dropdown-menu-button');
    if (menuButton) {
      menuButton.style.display = 'none';
    }

    const toolbars = excalidrawContainer.value.querySelectorAll('.App-toolbar-container');
    toolbars.forEach(toolbar => {
      toolbar.style.display = 'none';
    });

    const editableElements = excalidrawContainer.value.querySelectorAll('.App-menu__left');
    editableElements.forEach(element => {
      element.style.display = 'none';
    });

    // 在预览模式下隐藏编辑相关的自定义按钮，但保留导出按钮
    const customButtons = excalidrawContainer.value.querySelectorAll('.custom-toolbar-button');
    customButtons.forEach(button => {
      const isEditButton = button.title?.includes('保存') || button.title?.includes('清空') || button.title?.includes('全屏');
      if (isEditButton) {
        button.style.display = 'none';
      }
    });
  }, 100);
};

// 显示 Excalidraw UI 元素
const showExcalidrawUI = () => {
  if (!excalidrawContainer.value) return;

  const menuButton = excalidrawContainer.value.querySelector('.dropdown-menu-button');
  if (menuButton) {
    menuButton.style.display = '';
  }

  const toolbars = excalidrawContainer.value.querySelectorAll('.App-toolbar-container');
  toolbars.forEach(toolbar => {
    toolbar.style.display = '';
  });

  const editableElements = excalidrawContainer.value.querySelectorAll('.App-menu__left');
  editableElements.forEach(element => {
    element.style.display = '';
  });

  // 显示所有自定义按钮
  const customButtons = excalidrawContainer.value.querySelectorAll('.custom-toolbar-button');
  customButtons.forEach(button => {
    button.style.display = '';
  });
};

// 设置 MutationObserver 来监视 DOM 变化
const setupPreviewModeObserver = () => {
  if (!excalidrawContainer.value) return;

  previewModeObserver = new MutationObserver((mutations) => {
    if (previewMode.value) {
      hideExcalidrawUI();

      if (excalidrawAPI.value) {
        excalidrawAPI.value.updateScene({
          appState: {
            viewModeEnabled: true,
            readOnly: true,
          }
        });
      }
    }
  });

  previewModeObserver.observe(excalidrawContainer.value, {
    childList: true,
    subtree: true,
    attributes: true,
  });
};

// 为移动设备优化 Excalidraw 界面
const optimizeForMobile = () => {
  if (!excalidrawContainer.value) return;

  if (isMobile.value) {
    // 缩放工具栏
    const toolbars = excalidrawContainer.value.querySelectorAll('.App-toolbar-container');
    toolbars.forEach(toolbar => {
      toolbar.style.transform = 'scale(0.85)';
      toolbar.style.transformOrigin = 'left top';
    });

    // 调整工具按钮大小
    const menuButtons = excalidrawContainer.value.querySelectorAll('.ToolIcon_size_s');
    menuButtons.forEach(button => {
      button.style.paddingTop = '4px';
      button.style.paddingRight = '4px';
      button.style.paddingBottom = '4px';
      button.style.paddingLeft = '4px';
    });

    // 隐藏一些移动端不必要的工具
    const unnecessaryTools = excalidrawContainer.value.querySelectorAll('[data-testid="image"], [data-testid="embed"]');
    unnecessaryTools.forEach(tool => {
      if (tool) tool.style.display = 'none';
    });
  } else {
    const toolbars = excalidrawContainer.value.querySelectorAll('.App-toolbar-container');
    toolbars.forEach(toolbar => {
      toolbar.style.transform = '';
    });

    const menuButtons = excalidrawContainer.value.querySelectorAll('.ToolIcon_size_s');
    menuButtons.forEach(button => {
      button.style.paddingTop = '';
      button.style.paddingRight = '';
      button.style.paddingBottom = '';
      button.style.paddingLeft = '';
    });
  }
};

// 处理窗口大小变化
const handleResize = () => {
  const wasMobile = isMobile.value;
  checkMobile();

  if (excalidrawAPI.value && excalidrawContainer.value) {
    excalidrawAPI.value.updateScene({
      appState: {
        width: excalidrawContainer.value.clientWidth,
        height: excalidrawContainer.value.clientHeight,
      }
    });

    if (previewMode.value) {
      hideExcalidrawUI();
    }

    if (isFullscreen.value) {
      excalidrawAPI.value.updateScene({
        appState: {
          width: window.innerWidth,
          height: window.innerHeight,
        }
      });
    }

    optimizeForMobile();
  }

  // 重新计算浮动按钮位置
  calculateButtonPosition();
};

// 在组件卸载前清理
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);

  if (previewModeObserver) {
    previewModeObserver.disconnect();
    previewModeObserver = null;
  }

  document.removeEventListener('keydown', handleEscKey);
  excalidrawAPI.value = null;
});

// 切换预览模式
const togglePreviewMode = () => {
  if (!excalidrawAPI.value) {
    error.value = 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }

  previewMode.value = !previewMode.value;
};

// 显示保存对话框
const showSaveDialog = () => {
  if (!excalidrawAPI.value || previewMode.value) {
    error.value = previewMode.value ? '预览模式下无法保存绘图' : 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }
  if(!saveForm.local&&saveForm.accountId!=state.user?.id&&saveForm.id) {
    if(state.user?.id){
      error.value = '当前绘图不能更改';
    }else{
      error.value = '请先登录';
    }
    return;
  }
  const elements = excalidrawAPI.value.getSceneElements();
  if (elements.length === 0) {
    error.value = '画布为空，请先绘制内容';
    return;
  }
  saveForm.title =   saveForm.title||`绘图名称`
  loadProjectList('')
  loadBlogList('')
  showSaveModal.value = true;
};

const projectData = ref([]);
const loadProjectList=val=>{
  if(!state.user?.id){
    return
  }
  const target = []
  if(saveForm.blogId){
    target.push(saveForm.blogId);
  }
  projectList({page:{pageNum:1,pageSize:5},title:val,target:target}).then(res=>{
    if(res.code===200){
      projectData.value = res.data&&res.data.list || []
    }
  })
}

const blogData = ref([]);
const loadBlogList=val=>{
  if(!state.user?.id) {
    return
  }
  const target = []
  if (saveForm.blogId) {
    target.push(saveForm.blogId);
  }
  blogList({page: {pageNum: 1, pageSize: 5}, mine: true, title: val, target: target}).then(res => {
    if (res.code === 200) {
      blogData.value = res.data && res.data.list || []
    }
  })
}

// 确认保存
const confirmSave = (flag) => {
  formRef.value
      .validate()
      .then(() => {
        try {
          const elements = excalidrawAPI.value.getSceneElements();
          if (flag) {
            const drawing = {
              id: saveForm.id || Date.now(),
              title: saveForm.title.trim(),
              description: saveForm.description.trim(),
              blogId: saveForm.blogId,
              projectId: saveForm.projectId,
              local: flag,
              createdAt: saveForm.createdAt || Number(new Date().getTime() / 1000),
              content: JSON.stringify(elements),
            };
            const drawingIndex = draftList.value.findIndex(d => d.id === drawing.id);
            if (drawingIndex !== -1) {
              draftList.value[drawingIndex] = drawing;
            } else {
              draftList.value = [...draftList.value, drawing]
            }
            localStorage.setItem('excalidraw-demo', JSON.stringify(draftList.value));
            showSaveModal.value = false;
            error.value = '';
            resetForm()
            isDrafting.value = true
          } else {
            let changed = saveForm.id
            if (saveForm.local && saveForm.id) {
              saveForm.local = false;
              saveForm.id = ""
              saveForm.createdAt = 0
            }
            const formData = Object.assign({}, saveForm, {content: JSON.stringify(elements)})
            graphSave(formData).then(res => {
              if (res && res.code === 200) {
                if (changed) {
                  draftList.value = draftList.value.filter(drawing => drawing.id !== changed);
                  localStorage.setItem('excalidraw-demo', JSON.stringify(draftList.value));
                }
                showSaveModal.value = false;
                error.value = '';
                resetForm()
                if (changed) {
                  isDrafting.value = false
                }
              }
            }).finally(() => {
              pageNum.value = 1
              loadDrawings()
            })
          }
        } catch (e) {
          console.error('Error saving drawing:', e);
          error.value = `保存绘图时出错: ${e.message}`;
        }
      })
      .catch(error => {
        console.log('error', error, new Date().getTime() / 1000);
      });
};

// 取消保存
const cancelSave = () => {
  showSaveModal.value = false;
};

// 加载绘图
const loadDrawing = (drawing) => {
  if (!excalidrawAPI.value || previewMode.value) {
    error.value = previewMode.value ? '预览模式下无法加载绘图' : 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }

  saveForm.title = drawing.title;
  saveForm.description = drawing.description;
  saveForm.blogId = drawing.blogId;
  saveForm.projectId = drawing.projectId;
  saveForm.local = drawing.local
  saveForm.id = drawing.id;
  saveForm.accountId = drawing.accountId;
  saveForm.createdAt = drawing.createdAt || 0;

  try {
    const currentAppState = excalidrawAPI.value.getAppState();
    let elements = []
    if (drawing.content) {
      elements = JSON.parse(drawing.content);
      excalidrawAPI.value.updateScene({
        elements: elements,
        appState: {
          ...currentAppState,
          viewBackgroundColor: drawing.viewBackgroundColor || currentAppState.viewBackgroundColor,
        }
      });

    } else {
      graphCheck({id: drawing.id}).then(res => {
        if (res && res.code === 200) {
          const data = res.data || {};
          drawing.content = data.content;
          drawing.browseNumber = drawing.browseNumber ? drawing.browseNumber + 1 : 1;
          elements = JSON.parse(drawing.content);
        }
      }).finally(() => {
        excalidrawAPI.value.updateScene({
          elements: elements,
          appState: {
            ...currentAppState,
            viewBackgroundColor: drawing.viewBackgroundColor || currentAppState.viewBackgroundColor,
          }
        });
      });
    }

    error.value = '';
  } catch (e) {
    console.error('Error loading drawing:', e);
    error.value = `加载绘图时出错: ${e.message}`;
  }
};

// 删除绘图
const deleteDrawing = (item) => {
  if (item.local) {
    draftList.value = draftList.value.filter(drawing => drawing.id !== item.id);
    localStorage.setItem('excalidraw-demo', JSON.stringify(draftList.value));
  } else {
    graphDel({id: item.id}).then((res) => {
      if (res && res.code === 200) {
        // remoteTotal.value = remoteTotal.value - 1;
        // remoteList.value = remoteList.value.filter(drawing => drawing.id !== item.id);
        pageNum.value = 1
        loadDrawings()
      }
    }).finally(() => {
      if (item.id === saveForm.id) {
        resetForm()
      }
    })
  }
};

// 导出为PNG图片
const exportToPNG = () => {
  if (!excalidrawAPI.value) {
    error.value = 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }

  try {
    excalidrawAPI.value
        .exportToBlob({
          mimeType: 'image/png',
          exportWithDarkMode: false,
        })
        .then((blob) => {
          if (!blob) {
            throw new Error('导出失败，未能生成图片');
          }
          const url = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = `excalidraw-${Date.now()}.png`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(url);
        })
        .catch((e) => {
          console.error('Error in blob export:', e);
          error.value = `导出图片时出错: ${e.message}`;
        });
  } catch (e) {
    console.error('Error exporting image:', e);
    error.value = `导出图片时出错: ${e.message}`;
  }
};

// 导出为SVG图片
const exportToSVG = () => {
  if (!excalidrawAPI.value) {
    error.value = 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }

  try {
    excalidrawAPI.value
        .exportToSvg({
          exportWithDarkMode: false,
        })
        .then((svgElement) => {
          if (!svgElement) {
            throw new Error('导出失败，未能生成SVG');
          }
          const svgString = new XMLSerializer().serializeToString(svgElement);
          const blob = new Blob([svgString], {type: 'image/svg+xml'});
          const url = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = `excalidraw-${Date.now()}.svg`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(url);
        })
        .catch((e) => {
          console.error('Error in SVG export:', e);
          error.value = `导出SVG时出错: ${e.message}`;
        });
  } catch (e) {
    console.error('Error exporting SVG:', e);
    error.value = `导出SVG时出错: ${e.message}`;
  }
};

// 导出为JSON
const exportToJSON = () => {
  if (!excalidrawAPI.value) {
    error.value = 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }

  try {
    const elements = excalidrawAPI.value.getSceneElements();
    const appState = {...excalidrawAPI.value.getAppState()};

    if (!Array.isArray(appState.collaborators)) {
      appState.collaborators = [];
    }

    if (elements.length === 0) {
      error.value = '画布为空，请先绘制内容';
      return;
    }
    if (!state.user?.id && !saveForm.local) {
      error.value = '远程画布，请先登录!';
      return;
    }

    const exportData = {
      type: 'excalidraw',
      version: 2,
      source: 'Excalidraw Demo App Enhanced',
      elements,
      appState: {
        ...appState,
        exportWithDarkMode: false,
      },
    };

    const jsonString = JSON.stringify(exportData, null, 2);
    const blob = new Blob([jsonString], {type: 'application/json'});
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `excalidraw-${Date.now()}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    error.value = '';
  } catch (e) {
    console.error('Error exporting JSON:', e);
    error.value = `导出JSON时出错: ${e.message}`;
  }
};

// 切换全屏模式
const toggleFullscreen = () => {
  if (!excalidrawAPI.value) {
    error.value = 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }

  isFullscreen.value = !isFullscreen.value;

  if (isFullscreen.value) {
    enterFullscreen();
  } else {
    exitFullscreen();
  }
};

// 进入全屏模式
const enterFullscreen = () => {
  const container = excalidrawContainer.value;
  if (!container) return;

  container.classList.add('fullscreen-mode');

  if (excalidrawAPI.value) {
    excalidrawAPI.value.updateScene({
      appState: {
        width: window.innerWidth,
        height: window.innerHeight,
      }
    });
  }

  document.addEventListener('keydown', handleEscKey);
  optimizeForMobile();

  // 重新计算浮动按钮位置以确保在全屏模式下可见
  nextTick(() => {
    calculateButtonPosition();
  });
};

// 退出全屏模式
const exitFullscreen = () => {
  const container = excalidrawContainer.value;
  if (!container) return;

  container.classList.remove('fullscreen-mode');

  if (excalidrawAPI.value) {
    excalidrawAPI.value.updateScene({
      appState: {
        width: container.clientWidth,
        height: container.clientHeight,
      }
    });
  }

  document.removeEventListener('keydown', handleEscKey);

  // 重新计算浮动按钮位置
  nextTick(() => {
    calculateButtonPosition();
  });
};

// 处理 ESC 键退出全屏
const handleEscKey = (e) => {
  if (e.key === 'Escape' && isFullscreen.value) {
    toggleFullscreen();
  }
};

// 清空画布
const clearCanvas = () => {
  if (!excalidrawAPI.value || previewMode.value) {
    error.value = previewMode.value ? '预览模式下无法清空画布' : 'Excalidraw 组件未加载完成，请稍后再试';
    return;
  }
  try {
    excalidrawAPI.value.updateScene({elements: []});
    error.value = '';
  } catch (e) {
    console.error('Error clearing canvas:', e);
    error.value = `清空画布时出错: ${e.message}`;
  }
};
</script>

<style>
/* 基础样式 */
body {
  @apply bg-gray-50;
}

/* 预览模式样式 */
.preview-mode .excalidraw-container {
  @apply cursor-move;
}

/* 确保在预览模式下隐藏特定元素 */
.preview-mode .dropdown-menu-button,
.preview-mode .App-toolbar-container,
.preview-mode .App-menu__left {
  display: none !important;
}

/* 全屏模式样式 */
.fullscreen-mode {
  @apply fixed top-0 left-0 w-screen h-screen z-[9999] bg-white m-0 p-0 border-0 rounded-none shadow-none;
}

/* 确保全屏模式下 Excalidraw 组件占满整个屏幕 */
.fullscreen-mode .excalidraw {
  @apply w-screen h-screen;
}

/* 自定义工具栏按钮样式 */
.custom-toolbar-button {
  transition: all 0.15s ease-in-out;
}

.custom-toolbar-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.06) !important;
}

.custom-toolbar-button:active {
  transform: translateY(0);
}

/* 浮动操作按钮样式 */
.floating-action-button {
  @apply fixed bg-white border border-gray-300 rounded-md shadow-sm flex items-center justify-center cursor-pointer transition-all duration-150;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.floating-action-button:hover {
  @apply bg-gray-50 border-gray-400;
  transform: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.floating-action-button:active {
  @apply bg-gray-100;
  transform: scale(0.98);
}

/* 操作菜单覆盖层 */
.action-menu-overlay {
  @apply fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999];
}

/* 操作菜单样式 */
.action-menu {
  @apply bg-white rounded-lg shadow-xl max-w-xs w-full mx-4 max-h-[70vh] overflow-hidden border border-gray-200;
}

.action-menu-header {
  @apply flex items-center justify-between p-3 border-b border-gray-100 bg-gray-50;
}

.action-menu-item {
  @apply w-full flex items-center gap-3 p-3 rounded-md hover:bg-gray-50 transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed mx-2 my-1;
}

.action-menu-item:not(:disabled):hover {
  @apply bg-blue-50;
}

.action-icon {
  @apply text-lg flex-shrink-0 w-6 h-6 flex items-center justify-center;
}

.action-text {
  @apply font-medium text-gray-900 flex-1;
}

.action-description {
  @apply text-sm text-gray-500 mt-1 block w-full;
}

/* 文本省略样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .fullscreen-mode button {
    @apply p-1.5;
  }

  .fullscreen-mode .absolute.top-3.right-3 {
    @apply top-2 right-2;
  }

  .fullscreen-mode .excalidraw .App-toolbar-container {
    @apply scale-75 origin-top-left;
  }

  .floating-action-button {
    width: 28px;
    height: 51px;
  }

  .action-menu {
    @apply mx-2;
  }
}

/* 添加过渡效果 */
.fullscreen-mode {
  transition: all 0.3s ease-in-out;
}

/* 优化退出只读按钮样式 */
.group:hover svg {
  transform: scale(1.05);
}

/* 确保浮动按钮在所有模式下都可见 */
.floating-action-button {
  z-index: 9998 !important;
}

.fullscreen-mode .floating-action-button,
.preview-mode .floating-action-button {
  z-index: 10003 !important;
}

/* 滚动条样式优化 */
.action-menu-content::-webkit-scrollbar {
  width: 4px;
}

.action-menu-content::-webkit-scrollbar-track {
  background: #f1f5f9;
}

.action-menu-content::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 2px;
}

.action-menu-content::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>